<script>
import { findEmployeeAPI, getEnabledRoleListAPI, assignRolesAPI } from '@/api/employeeApi'

export default {
  name: 'RoleList',
  props: {
    isShowRole: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      /* 已经启用的角色列表 */
      roleList: [],
      /* 分配角色带给服务器的参数 */
      roleParams: {
        // 当前员工ID
        id: '',
        // 员工角色id数组
        roleIds: []
      }
    }
  },
  methods: {
    /* 获取员工详情的接口 */
    async fetchEmployeeDetail(id) {
      try {
        const { data } = await findEmployeeAPI(id)
        this.roleParams.roleIds = data.roleIds
        this.roleParams.id = id
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    /* 获取已经启用角色列表的回调函数 */
    async fetchEnabledRole() {
      try {
        const { data } = await getEnabledRoleListAPI()
        this.roleList = data
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    /* 对话框关闭时候的回调函数 */
    handleClose() {
      this.$emit('update:isShowRole', false)
    },
    /* 点击取消按钮的回调函数 */
    handleCancel() {
      this.$emit('update:isShowRole', false)
    },
    /* 点击确定按钮的回调函数 */
    async handleSubmit() {
      try {
        const { message } = await assignRolesAPI(this.roleParams)
        this.$message.success(message)
      } catch (e) {
        this.$message.error(e.message)
      }
    }
  },
  watch: {
    /* 监听isShowRole字段的变化 */
    isShowRole(newValue, oldValue) {
      if (!newValue) {
        this.roleParams.roleIds = []
        this.roleParams.id = ''
      }
    }
  }
}
</script>

<template>
  <el-dialog title="分配角色" :visible="isShowRole" append-to-body :close-on-click-modal="false" @close="handleClose">
    <el-checkbox-group v-model="roleParams.roleIds">
      <el-checkbox v-for="(item,index) in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

